<?php

namespace System\Core;

if (!defined('BASEPATH')) die('Access Denied.');

/**
 * µMVC Framework (c) 2011.
 * 
 * PHP5 MVC Framework software for PHP 5.2.17 or later
 * 
 * @package         µMVC
 * @filename        system/core/router.class.php
 * @copyright       Lanz (c) 2011.
 * 
 */

/**
 * Router class
 * The router class decides what controller and action method that should be
 * launched. It also redirects the the user to a 404 page if the specified
 * controller or method doesn't exists.
 * 
 * @package         µMVC
 * @subpackage      Core
 * @category        System
 * 
 */
class Router extends BaseSingleton
{

    /**
     * The URI class.
     * @var object
     */
    private $_URI;
    
    /**
     * The controller fetched from the URI string or the default index
     * controller
     * @var string
     */
    private $_controller;
    
    /**
     * The action fetched from the URI string or the default index action.
     * @var string
     */
    private $_action;
    
    /**
     * The argumets from the URI string.
     * @var array
     */
    private $_args;
    
    function __construct()
    {
        // Fetch the URI and define the routing.
        $this->_URI = URI::instance();
        $this->_setRouting();

        // Do some checks on the data we accuired.
        $this->_validateController($this->_controller);
        $this->_validateAction($this->_action);
    
        Log::instance()->write(Log::DEBUG, 'Router Class Initialized.');        
    }

    private function _setRouting()
    {
        $this->_controller = ($c = $this->_URI->getSegment(1)) ? $c : 'index';
        $this->_action = ($c = $this->_URI->getSegment(2)) ? $c : 'index';
    }
    
    private function _validateController($controller)
    {
        if (!is_readable(BASEPATH.'controllers'.DS.$controller.'.class.php'))
        {
            show_404($this->_URI->getUriString());
        }    
    }
    
    private function _validateAction()
    {
        if (!method_exists('\\System\\Controllers\\'.$this->_controller, $this->_action.'Action'))
        {
            show_404($this->_URI->getUriString());
        }
    }
    
    public function getController()
    {
        return $this->_controller;
    }
    
    public function getAction()
    {
        return $this->_action;
    }
    
    public function getArgs()
    {
        return $this->_args;
    }
}
?>
